package edu.hawaii.halealohacli;

import org.wattdepot.client.WattDepotClient;
import edu.hawaii.halealohacli.processor.Processor;

/**
 * The main execution class for the Hale Aloha CLI.
 * 
 * @author Chris Fang
 */
public class Main {

  WattDepotClient client;
  boolean connected;

  /**
   * Connects to a WattDepot server and starts up an instance of the command processor.
   * 
   * @param args The first arg should be the URL to a running WattDepot server
   * @throws Exception If problems occur communicating with the server
   */
  public static void main(String[] args) throws Exception {
    Main starter = new Main();
    System.out.format("%s%n", starter.setUpClient());
    if (starter.isConnected()) {
      // All is well, start up the processor
      Processor processor = new Processor(starter.getClient());
      processor.startProcessor();
    }
    else {
      // No connection was made, exit the application
      System.exit(1);
    }
  }

  /**
   * Returns the WattDepot client.
   * 
   * @return The WattDepot client
   */
  protected WattDepotClient getClient() {
    return this.client;
  }

  /**
   * Sets the connected flag to the boolean parameter.
   * 
   * @param connected The boolean value to set the connected flag to
   */
  protected void setConnected(boolean connected) {
    this.connected = connected;
  }

  /**
   * Returns the status of the client connection.
   * 
   * @return The boolean value the connected flag is set to
   */
  protected boolean isConnected() {
    return this.connected;
  }

  /**
   * Connects to a WattDepot client at a static URL.
   * 
   * @return A String message indicating if client-server connection succeeded
   */
  protected String setUpClient() {
    String healthMessage;
    String url = "http://server.wattdepot.org:8190/wattdepot/";
    // Create a client.
    client = new WattDepotClient(url);
    // Check to make sure a connection can be made.
    // If no connection, then exit right now.
    if (client.isHealthy()) {
      setConnected(true);
      healthMessage = "Connected successfully to the Hale Aloha WattDepot server.";
    }
    else {
      setConnected(false);
      healthMessage = "Could not connect to the Hale Aloha WattDepot server.";
    }
    return healthMessage;
  }
}
